# 保存当前工作目录
$originalLocation = Get-Location

# 设置工作目录为脚本所在目录的上一级
Set-Location (Join-Path $PSScriptRoot "..")


try {
  $folderName = "release"

  # 如果文件夹存在，则删除它
  if (Test-Path $folderName) {
    Remove-Item -Recurse -Force $folderName
  }

  # 创建文件夹
  New-Item -ItemType Directory -Path $folderName | Out-Null

  # 构建 windows 版本
  $Name=$args[0]
  if ([string]::IsNullOrEmpty($Name)) {
    $Name="sjy"
  }

  $windowsAppPath = Join-Path $folderName "windows"
  $AppName = Join-Path $windowsAppPath "$Name.exe"

  $env:GOOS = "windows"
  $env:GOARCH = "amd64"
  $env:APP_ENV = "production"
  & go build -x -o $AppName ./src/

  # 复制配置文件到windows目录
  if ($?) {
    $configPath = Join-Path $PSScriptRoot "..\etc\config"
    $dFolder_config = Join-Path $windowsAppPath "config"
    if (-Not (Test-Path $dFolder_config)) {
      New-Item -ItemType Directory -Path $dFolder_config | Out-Null
    }
    Copy-Item -Path "$configPath\*" -Destination "$dFolder_config" -Recurse -Force
  }
  
}
catch {
  # 捕获异常并将异常信息写入日志文件
  $errorMessage = $_.Exception.Message
  $errorStackTrace = $_.Exception.StackTrace
  $errorDetails = "Action: $action`nError: $errorMessage`nStack Trace: $errorStackTrace"
  Write-Output "$errorDetails"
  Write-Output "Build go failed!!!!"
  exit 1
}
finally {
  # 恢复原始工作目录
  Set-Location $originalLocation
}
